﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using Mrc.Common;
using Newtonsoft.Json;

namespace Mrc.SqlSurging
{
    public static class ConnectionConfigManager
    {
        public static Dictionary<string,ConnectionConfig> _DbConnectionConfig { get; set; } = new Dictionary<string,ConnectionConfig>(StringComparer.OrdinalIgnoreCase);

        public static void Init(this SqlSurgarConnectionOptions option)
        {
            option.AdminConnectionStrList.ForEach(item =>Set(item));
            option.AppConnectionStrList.ForEach(item =>Set(item));
        }

        private static void Set(SurgarConnectionString surgarConnectionString)
        { 
           _DbConnectionConfig.Add(surgarConnectionString.Key,JsonConvert.DeserializeObject<ConnectionConfig>(surgarConnectionString.Connection));
        }

        /// <summary>
        /// 获取配置信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static ConnectionConfig Get(string key)
        {
            if (!_DbConnectionConfig.ContainsKey(key)) throw new MrcException($"获取{key}标签数据库配置失败");
            return _DbConnectionConfig[key];
        }

        /// <summary>
        /// 添加或更新数据库连接配置
        /// </summary>
        /// <param name="key"></param>
        /// <param name="connectionConfig"></param>
        public static void AddOrUpdate(string key, ConnectionConfig connectionConfig)
        {
            if(_DbConnectionConfig.ContainsKey(key))
            {
                _DbConnectionConfig[key] = connectionConfig;
            }
            else 
            {
                _DbConnectionConfig.Add(key, connectionConfig);
            }
        }

        /// <summary>
        /// 后台数据库连接配置
        /// </summary>
        public static ConnectionConfig AdminInstance { get { return Get("admin");}}

        /// <summary>
        /// 用户数据库连接配置
        /// </summary>
        public static ConnectionConfig AppInstance { get { return Get("app");} }

    }
}
